import { IFeidaoAiNodejsPage } from '@feidao/web/interfaces';
import call_service from '@feidao/web/atom/nodejs/msg/call-service';
import { spaceid } from '../atom-web/config';
import set_cookie from "@feidao/web/atom/nodejs/server/set-cookie";
import redirect from "@feidao/web/atom/nodejs/server/redirect";
import return_success from "@feidao/web/atom/nodejs/server/return-success";
import return_fail from "@feidao/web/atom/nodejs/server/return-fail";

export default async function na001(fd: IFeidaoAiNodejsPage, ...args: any[]) {
	const params = fd.data.params;
	if (JSON.stringify(params) !== '{}') {
		if (params.code) {
			const param = {
				logintype: "weixin_pc",
				code: params.code,
				spaceid: 'spaceid'
			};
			try {
				const res = await call_service<{ msg: string, user: { sessionid: string; } }>(fd.data.actionid, fd.data.sessionid, spaceid, 'busiservice.flippedclass.weixinlogin', param);
				if (res.msg === '微信登录成功') {
					const user_info = res.user;
					const sessionid = user_info.sessionid;
					const s = { sessionid };
					const c = set_cookie(s);
					// 跳转到其他页面
					const backurl = fd.data.params.backurl;
					const r = redirect(backurl ? (decodeURIComponent(backurl)) : 'home.html');
					return return_success(Object.assign({}, c, r));
				}
				if (res.msg === '该微信未绑定用户') {
					const data = '该微信未绑定用户';
					return return_fail({ data });
				}
			} catch (err) {
				const data = JSON.stringify(err);
				return return_fail({ data });
			}
		}
	}
}
